iT邦幫忙

1

[C] nanomsg Hello World!

  • 分享至 

  • xImage
  •  

前言

nanomsg的前身是ZeroMQ。本人也是先接觸到ZeroMQ,畢竟ZeroMQ相關資源豐富,較易上手。官方提供了很好的解釋兩者之間的差異(Differences between nanomsg and ZeroMQ)。

無痛從ZeroMQ轉換至nanomsg

由於nanomsg的sample code整理較少,故引用ZeroMQ範例,並改成nanomsg。

//  Hello World server
#include <stdio.h>
#include <thread>
#include "nn.h"
#include "reqrep.h"

int main(void)
{
	int responder = nn_socket(AF_SP, NN_REP);
	int rc = nn_bind(responder, "tcp://127.0.0.1:5555");
	if (rc < 0) exit(1);

	while (1) {
		char *buffer = NULL;
		nn_recv(responder, &buffer, NN_MSG, 0);
		printf("Received %s\n", buffer);
		nn_freemsg(buffer);
		std::this_thread::sleep_for(std::chrono::milliseconds(1));
		nn_send(responder, "World", 5, 0);
	}
	return 0;
}
//  Hello World client
#include <stdio.h>
#include "nn.h"
#include "reqrep.h"

int main(void)
{
	printf("Connecting to hello world server\n");
	int requester = nn_socket(AF_SP, NN_REQ);
	int rc = nn_connect(requester, "tcp://127.0.0.1:5555");

	for (int i = 0;; ++i) {
		char *buffer = NULL;
		printf("Sending Hello %d\n", i);
		nn_send(requester, "Hello", 5, 0);
		nn_recv(requester, &buffer, NN_MSG, 0);
		printf("Received %s %d\n", buffer, i);
        nn_freemsg(buffer);
	}
	nn_close(requester);
	return 0;
}

比較後可以發現,API其實很好置換。

ZeroMQ nanomsg
zmq_socket nn_socket
zmq_bind nn_bind
zmq_connect nn_connect
zmq_send nn_send
zmq_recv nn_recv
zmq_close nn_close
zmq_ctx_new -
zmq_ctx_destroy -

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言